﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace Backup
{
    using System.Collections.ObjectModel;
    using System.IO;
    using System.Xml;
    using System.Xml.Serialization;
    using BackupLib;

    /// <summary>
    /// Interaction logic for Window1.xaml
    /// </summary>
    public partial class Window1 : Window
    {
        private BackupProject Project { get; set; }

        public Window1()
        {
            InitializeComponent();
        }
        

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            Project.AddTask(new BackupWorker());
        }

        public static void Serialize(BackupProject obj)
        {
            XmlSerializer serializer = new XmlSerializer(typeof(BackupProject));
            XmlTextWriter writer = new XmlTextWriter("backup.xml",Encoding.UTF8);
            writer.Formatting = Formatting.Indented;
            serializer.Serialize(writer,obj);
            writer.Close();
        }
        
        public static BackupProject Deserialize()
        {
            XmlSerializer serializer = new XmlSerializer(typeof(BackupProject));
            XmlTextReader reader = new XmlTextReader("backup.xml");
            BackupProject retval;
            try
            {
                retval = serializer.Deserialize(reader) as BackupProject;
            }
            catch (Exception)
            {
                retval = new BackupProject();
            }
            reader.Close();
            return retval;
        }

        private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            Serialize(Project);
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            Project = Deserialize();
            lstSource.ItemsSource = Project.Tasks;
        }
    }
}
